package org.zsl.dao;

import org.zsl.model.User;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDAO2 implements IUserDAO{
    @Override
    public Boolean insert(User user) {
        String sql = "insert into user(username,password,role_id) value(?,?,?)";
        Object[] params = new Object[]{
           user.getUsername(),user.getPassword(),user.getRoleId()
        };


        return DBUtil.uptate(sql,params);
    }

    @Override
    public Boolean delete(Integer userId) {
        return null;
    }

    @Override
    public Boolean update(User user) {
        return null;
    }

    @Override
    public ResultSet selectAll() {
        return DBUtil.query("select * from user",null);
    }

    @Override
    public List<User> selectAll2() {
         ResultSet resultSet = this.selectAll();
         List<User> list = new ArrayList<>();

             try {

                 while (resultSet.next()){

                     /**
                      *  把数据库的一条记录
                      *  转化成 一个Java对象
                      */

                     User user = convertToUser(resultSet);

                     list.add(user);
                 }

             } catch (SQLException throwables) {
                 throwables.printStackTrace();
             }



        return list;
    }

    private User convertToUser(ResultSet resultSet) throws SQLException {
        User user = new User();
        user.setUsername(resultSet.getString("username"));
        user.setPassword(resultSet.getString("password"));
        user.setRoleId(resultSet.getInt("role_id"));
        return user;
    }
}
